const express = require("express")
const cors = require("cors")
const app = express()
const mysql = require("mysql")
const bodyparser = require("body-parser")
const pool = mysql.createPool(
    {
        host:'127.0.0.1',
        port:'3306',
        user:'root',
        password:'Ab916536',
        database:'chatroom'
    }
)
app.listen(9090)
app.use(cors())
app.use(bodyparser.urlencoded({
        extended:false
}))
app.post("/querymsg",function (req,res){
        fromid = req.body.from
        toid = req.body.to
        if(toid==0){
                sql = "select * from msg where toid = 0"
                pool.query(sql,function (err,result){
                        if(err) console.log(err)
                        // console.log(result)
                        res.json(result)
                })
        }else{
                sql = "select * from msg where (fromid = ? and toid =?) or (fromid = ? and toid = ?)"
                pool.query(sql,[fromid,toid,toid,fromid],function (err,result){
                        if(err) console.log(err)
                        // console.log(result)
                        res.json(result)
                })
        }

})
app.post("/sendmsg",function(req,res){
        msg = req.body.msg
        fromid = req.body.from
        toid = req.body.to
        fromusername = req.body.fromusername
        console.log(fromusername)
        sql = "insert into msg(msg,fromid,toid,fromusername) values(?,?,?,?)"
        pool.query(sql,[msg,fromid,toid,fromusername],function (err,result){
                if(err) console.log(err)
                res.json({msg:"send success!"})
        })
})
app.post("/reg",function (req,res){
        username = req.body.username
        password = req.body.password
        age = req.body.age
        hobby = req.body.hobby
        sex = req.body.sex
        sql  = "insert into user(username,password,age,hobby,sex) values(?,?,?,?,?)"
        pool.query(sql,[username,password,age,hobby,sex],function (err,result){
                if(err) console.log(err)
                res.json(result)
        })
})
app.post("/login",function (req,res){
        username = req.body.username
        password = req.body.password
        sql = "select * from user where username=? and password = ?"
        pool.query(sql,[username,password],function (err,result){
                if(err) console.log(err)
                res.send(result)
        })
})
app.post("/getusers",function (req,res){
        sql = "select * from user"
        pool.query(sql,function (err,result){
                if(err) console.log(err)
                res.send(result)
        })
})
console.log("server is running...")